<template>
	<div class="input-box">
		<div class="input-panel border-1px-top">
			<div class="input">
				<div class="edit-input" ref="editInput" contenteditable @click="onClick" @keyup="onKeyUp" @blur="setTxt" :placeholder='c_placeholder ? c_placeholder : placeholder'></div>
			</div>
			<div class="send">
				<div>
					<i class="iconfont" :class="unfold ? 'icon-keyboard_icon' : 'icon-smiling'" @click="open" />
				</div>
				<div class="txt" :class="canSend ? 'can' : ''" @click="send">
					<span>发送</span>
				</div>
			</div>
		</div>
		<van-swipe :loop="false" ref="swipe" class="border-1px-top" :class="unfold ? '' : 'unfold'">
			<van-swipe-item v-for="(slider, index) of sliderPage" :key="index">
				<div class="emoji-panel">
					<div v-for="(row,index) of slider" :key="index" class="row">
						<div v-for="(cell,j) of row" :key="j" class="cell">
							<img v-if="cell.src" :data-name='cell.name' :src="cell.src" @click="addEmoji(cell)" />
							<i class="iconfont icon-xiangzuo" v-if="cell.delete" @click="del"/>
						</div>
					</div>
				</div>
			</van-swipe-item>
		</van-swipe>
	</div>
</template>
<script>
import { randomNum } from '@/utils'
import { emojis } from '@/utils/emoji'

const placeholders = ['说点什么吧,也许TA都听得到', '这一次也许就是你上热评了', '听说爱评论的人粉丝多', '随乐而起, 有感而发', '听了这么多, 可能你有话要说']

export default {
	data() {
		return {
			txt: '',
			unfold: false,
			lastEditRange: null,
			c_placeholder: null
		}
	},
	computed: {
		placeholder() {
			return placeholders[randomNum(0, placeholders.length - 1)]
		},
		canSend() {
			return this.txt !== ''
		},
		sliderPage() {
			let keys = Object.keys(emojis)
			let page = Math.ceil(keys.length / (4 * 7))
			let count = 0

			let slider = []
			for (let index = 0; index < page; index++) {
				let rows = []
				for (let row = 0; row < 4; row++) {
					let cells = []
					for (let cell = 0; cell < 7; cell++) {
						let name = keys[count]
						let src = emojis[name]
						if (src) {
							src = require(`@/assets/face/${src}`)
						}

						cells.push({ src, name })
						count++
						// if (row === 3 && cell === 6) {
						// 	src = require(`@/assets/face/back.png`)
						// 	cells.push({ delete: true })
						// } else {
						// 	cells.push({
						// 		src,
						// 		name
						// 	})
						// 	count++
						// }
					}
					rows.push(cells)
				}
				slider.push(rows)
			}
			return slider
		}
	},
	methods: {
		open() {
			this.unfold = !this.unfold
			this.keepRang()
		},
		onClick() {
			this.lastEditRange = window.getSelection().getRangeAt(0)
		},
		onKeyUp() {
			this.setTxt()
			this.lastEditRange = window.getSelection().getRangeAt(0)
		},
		focus() {
			this.$refs.editInput.focus()
		},
		blur() {
			this.$refs.editInput.blur()
		},
		clear() {
			this.$refs.editInput.innerHTML = ''
			this.$refs.editInput.blur()
			this.c_placeholder = null
		},
		send() {
			if (!this.canSend) return
			this.$emit('send', this.parse(this.$refs.editInput.childNodes))
			this.clear()
			this.unfold = false
			this.lastEditRange = null
		},
		addEmoji({ src, name }) {
			const img = new Image()
			img.src = src
			img.dataset.name = name
			this.$nextTick(() => {
				this.insertHtmlAtCaret(img)
				this.setTxt()
			})
		},
		setTxt() {
			this.txt = this.$refs.editInput.innerHTML
		},
		del() {
			let { startOffset, startContainer } = window.getSelection().getRangeAt(0)

			if (startContainer.className === 'edit-input') {
				let node = this.$refs.editInput.childNodes[startOffset - 1]
				this.$refs.editInput.removeChild(node)
			} else if (this.isTextNode(startContainer)) {
				let textContent = startContainer.textContent
				let arr = textContent.split('')
				arr.splice(startOffset - 1, 1)
				textContent = arr.join('')
				startContainer.textContent = textContent
				if (textContent.length === 0) {
					this.$refs.editInput.removeChild(startContainer)
				}
			}
			// this.keepLastIndex()
		},
		isImgNode({ nodeName }) {
			return nodeName === "IMG"
		},
		isTextNode({ nodeName }) {
			return nodeName === '#text'
		},
		isDivNode({ nodeName }) {
			return nodeName === 'DIV'
		},
    /**
     * 光标处插入内容
     * @param html 需要插入的内容
     */
    insertHtmlAtCaret(html) {
      let sel, range;
      if (!this.$refs.editInput.childNodes.length) {
        this.$refs.editInput.focus();
      }
      if (window.getSelection) {
        // IE9 and non-IE
        sel = window.getSelection();

        if (sel.getRangeAt && sel.rangeCount) {
          range = sel.getRangeAt(0);
          range.deleteContents();
          let el = document.createElement("div");
          el.appendChild(html);
          var frag = document.createDocumentFragment(),
            node,
            lastNode;
          while ((node = el.firstChild)) {
            lastNode = frag.appendChild(node);
          }
          range.insertNode(frag);
          if (lastNode) {
						range = range.cloneRange()
						range.setStartAfter(lastNode)
						range.collapse(true)
						sel.removeAllRanges()
						sel.addRange(range)
						this.lastEditRange = range
          }
        }
      } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(html);
      }

      // this.handleInput();
		},
		parse(childNodes) {
			
			let txt = ''

			if (!childNodes) return txt

			for (const childNode of childNodes) {
				if (this.isImgNode(childNode)) {
					txt += childNode.dataset['name']
				} else if (this.isTextNode(childNode)) {
					txt += childNode.textContent
				} else if (this.isDivNode(childNode)) {
					txt += '\n'
					txt += this.parse(childNode.childNodes)
				}
			}
			return txt
		},
		keepRang() {
			if (!this.lastEditRange) return
			this.$nextTick(() => {
				let sel = window.getSelection()
				sel.removeAllRanges()
				sel.addRange(this.lastEditRange)
			})
		},
		setPlaceholder(text) {
			this.c_placeholder = text
			this.focus()
		}
	}
}
</script>
<style lang="less" scoped>
@import '~@/style/variable.less';
.input-box{
	position: fixed;
	width: 100%;
	bottom: 0;
	background: white;
	box-sizing: border-box;	
	display: flex;
	flex-direction: column;
	font-size: @font-size-small;
	color: @text-color-light;
	.input-panel{
		width: 100%;
		display: flex;
		min-height: 35px;
		overflow: auto;
		.input {
			flex: 1;
			background-color: white;
			width: 0;
			height: 100%;
			border: none;
			padding: 5px;
			max-height: 60px;
			overflow: auto;
		}
		.edit-input{
			min-height: 35px;
			line-height: 35px;
			word-break: break-all;
			img{
				margin-right: 5px;
			}
		}
		.edit-input:focus{
			outline: none;
		}
		.edit-input:empty::before {
			content: attr(placeholder);
		}
		.send{
			width: 60px;
			display: flex;
			background-color: white;
			padding-right: 8px;
			>div{
				position: relative;
				flex: 1;
				height: 100%;
			}
			i{
				font-size: 1.5em;
			}
			i,span{
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translateY(-50%) translateX(-50%);
				white-space: nowrap;
			}
		}
		.can{
			color: @text-color;
		}
	}
	.unfold{
		height: 0px;
	}
	.emoji-panel{
		height: 200px;
		.row{
			height: 25%;
			.cell{
				position: relative;
				float: left;
				width: 14.2%;
				height: 100%;
				text-align: center;
				img, i{
					position: absolute;
					left: 50%;
					top: 50%;
					transform: translateY(-50%) translateX(-50%);
				}
			}
		}
	}
}
</style>